package pers.cyril.jdb.server.netty.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import pers.cyril.jdb.common.util.SessionUtils;

/**
 * auth handler
 *
 * @author yichao wang
 */
@ChannelHandler.Sharable
@Slf4j
public class CheckSessionHandler extends ChannelInboundHandlerAdapter {

    public static final CheckSessionHandler INSTANCE = new CheckSessionHandler();

    private CheckSessionHandler() {

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (SessionUtils.hasSession(ctx.channel())) {
            log.info("session check success, username={}", SessionUtils.getSession(ctx.channel()).getUsername());
            super.channelRead(ctx, msg);
            ctx.channel().pipeline().remove(this);
        } else {
            log.info("session check fail, will close connection");
            ctx.channel().close();
        }
    }


}
